package com.grm.service.impl;

import com.grm.entity.User;
import com.grm.servie.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CountDownLatch;

@Service
@Slf4j
public class AsyncServiceImpl implements AsyncService {
//    @Autowired
//    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Override
    @Async("asyncServiceExecutor")
    public void executeAsync(List<User> childUsers, CountDownLatch countDownLatch) {
        try {
            long begin = System.currentTimeMillis();
            //异步线程要做的事情,插入数据库
            // 1. mybatis批量插入
            //userMapper.batchInsert(childUsers);
            // 2. mybatis-plus批量插入
            userService.saveBatch(childUsers);
            long end = System.currentTimeMillis();
            log.info("batch insert child users time = {} ms", (end - begin));
        } catch (Exception e) {
            log.error("batch insert users error = {}", e.getMessage());
        } finally {
            // 很关键, 无论上面程序是否异常必须执行countDown,否则await无法释放
            countDownLatch.countDown();
        }
    }
}